package com.hjh.gameforum.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hjh.gameforum.result.Result;
import com.hjh.gameforum.utils.CurrentHolder;
import com.hjh.gameforum.utils.JwtTokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(JwtInterceptor.class);

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    private void writeErrorResponse(HttpServletResponse response, int code, String message) throws Exception {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json;charset=UTF-8");
        Result<Void> result = Result.error(code, message);
        String json = new ObjectMapper().writeValueAsString(result);
        PrintWriter writer = response.getWriter();
        writer.write(json);
        writer.flush();
        writer.close();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token)) {
            writeErrorResponse(response, 401, "未提供认证token");
            return false;
        }

        try {
            boolean isValid = jwtTokenUtil.validateToken(token);
            if (!isValid) {
                writeErrorResponse(response, 401, "token已失效，请重新登录");
                return false;
            }
            Long userId = jwtTokenUtil.getUserIdFromToken(token);
            String username = jwtTokenUtil.getUsernameFromToken(token);
            request.setAttribute("userId", userId);
            request.setAttribute("username", username);
            CurrentHolder.setCurrentId(userId);
            return true;
        } catch (Exception e) {
            writeErrorResponse(response, 401, "token已失效，请重新登录");
            return false;
        }
    }

}